package com.refid.api.cmd;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import com.refid.api.util.BuleUtil;

public class Y13RCmd extends Cmd {
	public static final String CMD_START = "7F";// 命令开始
	public static final String REP_START = CMD_START + " " + CMD_START;//

	@Override
	public HashSet<String> cmdTOEcp(List<String> list) {
		HashSet<String> set = new HashSet<String>();
		if (list == null || list.size() == 0)
			return set;
		String cmdType = null;
		String cmd = null;
		String ecp = null;
		for (int i = 0; i < list.size(); i++) {
			cmd = list.get(i);
			if (cmd.length() < 4 * 4)
				continue;
			cmdType = cmd.substring(3 * 3, 3 * 3 + 2);
			if ("90".equals(cmdType)) {
				ecp = cmd.substring(3 * 7, cmd.length() - 3 * 1);
				set.add(ecp);
			}
		}
		return set;
	}

	@Override
	public List<String> cmds(String hexs) {
		List<String> list = new ArrayList<String>();
		hexs = BuleUtil.trimTONull(hexs);
		if (hexs == null)
			return list;
		hexs = hexs.replaceAll("REP_START", REP_START);
		int index = hexs.indexOf(CMD_START);
		String hexLen = null;
		String cmd = null;
		int len = 0;
		String chekSum = null;
		String chekSum_ = null;
		while (index != -1) {
			hexLen = hexs.substring(index + 3, index + 3 + 2);
			len = hexToInt(hexLen);
			cmd = hexs.substring(index, index + 2 + 3 + len * 3);
			chekSum = cmd.substring(cmd.length() - 2);
			chekSum_ = checkSum(cmd.substring(0, cmd.length() - 2));
			if (chekSum.equalsIgnoreCase(chekSum_)) {
				list.add(cmd);
			}
			index = hexs.indexOf(CMD_START, index + cmd.length());
		}
		return list;

	}

	@Override
	protected String repairCmd(String hexs) {
		hexs = BuleUtil.trimTONull(hexs);
		String cmd = CMD_START + " ";
		int len = hexs.split(" ").length + 1;
		String len_ = byteToHex((byte) len);
		String checkSum = checkSum(len_ + " " + hexs);
		cmd = cmd + len_ + " " + hexs.replaceAll(CMD_START, REP_START);
		cmd = cmd + " " + checkSum;
		return cmd;
	}

	@Override
	public String checkSum(String hexs) {
		String[] cmdFirstpart = hexs.split(" ");
		Byte rst = null;
		for (int i = 0; i < cmdFirstpart.length; i++) {
			if (rst == null) {
				rst = hexToByte(cmdFirstpart[i]);
			} else {
				rst = (byte) (rst ^ hexToByte(cmdFirstpart[i])); // address
			}
		}
		return byteToHex((byte) rst);
	}

	public static void main(String[] args) throws Exception {
		Y13RCmd cmd = new Y13RCmd();
		System.out.println(cmd.repairCmd("00 90 00 04 00 FD D6 E1 72"));
		// 7F 0A 00 90 00 04 00 FD D6 E1 72 26
		System.out.println(Integer.parseInt("DDCCBBAA", 16));

	}

}
